﻿

$.fn.ShowMap = function (params) {
    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();
    var map, geocoder, myLocation;

    var defaults = {
        selector: this,
        width: 500,
        height: 500,
        target_marker: "select",
        lat: 10.4189522,
        lng: 105.6442166
    };

    var settings = $.extend({}, defaults, params);
    initialize = function (options) {
        geocoder = new google.maps.Geocoder();
        $(options.selector).append('<span id="btn-my-location">Vị trí của tôi</span>');
        var mapcanvas = document.createElement('div');
        mapcanvas.id = 'mapcanvas';
        mapcanvas.style.height = options.height + 'px';
        mapcanvas.style.width = options.width + 'px';
        $(options.selector).append(mapcanvas);
        
        myLocation = new google.maps.LatLng(settings.lat, settings.lng);
        var mapOptions = {
            zoom: 14,
            center: myLocation
        }
        map = new google.maps.Map(document.getElementById('mapcanvas'), mapOptions);
     
        var address, markerShop;
        $(options.target_marker).children().each(function (index) {
            markerAddress($(this).val(), $(this).text());
        });
        
        directionsDisplay = new google.maps.DirectionsRenderer();
        directionsDisplay.setMap(map);
        
    }

    markerAddress = function (address, shopname) {
        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,
                    title: shopname + "\n" + results[0].formatted_address
                });
            }
        });
    }
    setCenterMap = function (address) {
        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
            }
        });
    }
    google.maps.event.addDomListener(window, 'load', initialize(settings));
    
    getMyLocation = function () {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                myLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                var markerMyLocation = new google.maps.Marker({
                    position: myLocation,
                    map: map,
                    title: "You are here!"
                });
                map.setCenter(myLocation);
                $(settings.selector).find('#btn-my-location').text("Vị trí của tôi");
            }, function (msg) {
                myLocation = new google.maps.LatLng(settings.lat, settings.lng);
                var markerMyLocation = new google.maps.Marker({
                    position: myLocation,
                    map: map,
                    title: "You are here!"
                });
                map.setCenter(myLocation);
                $(settings.selector).find('#btn-my-location').text("Vị trí của tôi");
            }, { enableHighAccuracy: true, timeout: 3000, maximumAge: 0 });
        } else {
            alert("Trình duyệt không hỗ trợ");
        }
    }

    function calcRoute(obj) {
        var selectedMode = $(settings.selector).find(settings.target_marker).val();
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                var request = {
                    origin: myLocation,
                    destination: selectedMode,
                    travelMode: google.maps.TravelMode.DRIVING
                };
                directionsService.route(request, function (response, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        directionsDisplay.setDirections(response);
                        try {
                            var route = response.routes[0];
                            var str = '<strong>Khoảng cách: </strong>' + route.legs[0].distance.text + ', <strong>Thời gian: </strong>' + route.legs[0].duration.text;
                            $(settings.selector).find('[data-result]').empty().append(str);
                        } catch (error) {
                            $(settings.selector).find('[data-result]').empty().append('Không tính được khoảng cách');
                        }
                    }
                });
                //$(obj).text('Vẽ đường');
            }, function () {
                var request = {
                    origin: myLocation,
                    destination: selectedMode,
                    travelMode: google.maps.TravelMode.DRIVING
                };
                directionsService.route(request, function (response, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        directionsDisplay.setDirections(response);
                        try {
                            var route = response.routes[0];
                            var str = '<strong>Khoảng cách: </strong>' + route.legs[0].distance.text + ', <strong>Thời gian: </strong>' + route.legs[0].duration.text;
                            $(settings.selector).find('[data-result]').empty().append(str);
                        } catch (error) {
                            $(settings.selector).find('[data-result]').empty().append('Không tính được khoảng cách');
                        }
                    }
                });
                //$(obj).text('Vẽ đường');
            }, { enableHighAccuracy: true, timeout: 3000, maximumAge: 0 });
        } else {
            alert("Trình duyệt không hỗ trợ");
        }
    }

    $(settings.selector).find("[data-calcRoute]").click(function () {
        if ($(this).attr('data-calcRoute')) {
            //$(this).text('Loading...');
            $(settings.selector).find('[data-result]').empty().text('Loading...');
            calcRoute(this);
        }
    });
    $(settings.selector).find('#btn-my-location').click(function () {
        $(this).text('Loading...');
        getMyLocation();
    });
    
    $(settings.target_marker).change(function () {
        setCenterMap($(this).val());
    });

}
